//
//  WKWebDemoController.m
//  advertiseDemo
//
//  Created by zhangliang on 16/11/29.
//  Copyright © 2016年 zhouhuanqiang. All rights reserved.
//

#import "WKWebDemoController.h"
#import <WebKit/WebKit.h>


@interface WKWebDemoController ()
<
WKUIDelegate,
WKNavigationDelegate,
UIScrollViewDelegate,
WKScriptMessageHandler
>

@property (nonatomic, strong) WKWebView *wkWebView;

@end

@implementation WKWebDemoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"加载WKWebView";
    
    WKWebViewConfiguration *configuretion = [WKWebViewConfiguration new];
    configuretion.preferences = [[WKPreferences alloc]init];
    configuretion.preferences.minimumFontSize = 10;
    configuretion.preferences.javaScriptEnabled = YES;
    configuretion.processPool = [[WKProcessPool alloc]init];
    // 默认是不能通过JS自动打开窗口的，必须通过用户交互才能打开
    configuretion.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    
    // 通过js与webview内容交互配置
    configuretion.userContentController = [[WKUserContentController alloc] init];
    //注入JS对象名称ZhangliangTest，js_alert, SuperCall
    [configuretion.userContentController addScriptMessageHandler:self name:@"ZhangliangTest"];
    [configuretion.userContentController addScriptMessageHandler:self name:@"js_alert"];
    [configuretion.userContentController addScriptMessageHandler:self name:@"SuperCall"];
    
    
    CGSize size = [[UIScreen mainScreen] bounds].size;
    _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height) configuration:configuretion];
    _wkWebView.UIDelegate = self;
    _wkWebView.navigationDelegate = self;
    _wkWebView.allowsBackForwardNavigationGestures = YES;
    [_wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    _wkWebView.clipsToBounds = YES;
    _wkWebView.scrollView.clipsToBounds = NO;
    [self.view addSubview:self.wkWebView];
    
    // 本地HTML文件
    NSURL *path =[[NSBundle mainBundle] URLForResource:@"javascript_WKweb" withExtension:@"html"];
    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:path]];
    // 公司测试url
    //NSURL *url = [NSURL URLWithString:@"http://192.168.10.120/test/TestSupperCall.html"];
    //[self.wkWebView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"SuperCall"]) {
        NSLog(@"========== js-SupperCall发送给iOS的数据 ========\n%@",message.body);
    }
    if ([message.name isEqualToString:@"ZhangliangTest"]) {
        // 打印传过来的参数，只支持NSNumber，NSSTring，NSDate, NSARray,NSDictionary,NSNull
        NSLog(@"========== js-ZhangliangTest发送给iOS的数据 ========\n%@",message.body);
    }
    if ([message.name isEqualToString:@"js_alert"]) {
        NSLog(@"<<<<<<<<<< js——jsalert发给iOS的数据 >>>>>>>>>>>>>>");
    }
}

// js端调用alert函数会触发此代理方法
// js端调用alert时所传参数通过message拿到
// 在native得到结果后，需要回调js,是通过completionHandler回调
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"====%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alerfromjs" message:@"js调用alert" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
    NSLog(@"======%@", message);
}
// js端调用confirm函数会触发此代理方法
// 通过message可以拿到js端所传的参数
// 在IOS端显示原生alert的YES/NO后通过通过completionHandler回调JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    NSLog(@"====%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirmfromjs" message:@"js调用confrim" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
    NSLog(@"======%@", message);
    
}
// js端调用prompt函数时会触发此方法
// 会要求输入一段文本
// 在native输入得到文本内容后，通过completionHandler回调给js
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    NSLog(@"====%s", __FUNCTION__);
    NSLog(@"prompt = %@", prompt);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textInput" message:@"js调用文本输入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor greenColor];
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    NSLog(@"页面开始加载");
}
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    NSLog(@"内容正在加载当中");
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    NSLog(@"页面加载完成");
}
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"页面加载失败");
}
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
    
}

//// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    //如果进行的是跳转类的url 进行跳转
    NSURL *url = navigationAction.request.URL;
    if (![url.scheme isEqualToString:@"http"] &&
        ![url.scheme isEqualToString:@"https"]) {
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        // 这里就不写进度条了，把加载的进度打印出来，进度条可以自己加上去！
        CGFloat newProgress = [[change objectForKey:NSKeyValueChangeNewKey] floatValue];
        NSLog(@">>>>>>>>>>>>>> === %f",newProgress);
    }
}

@end
